package com.service;

import com.conf.AppInterceptor;
import com.conf.Constant;
import com.dao.UserDao;
import com.dao.UserRoleDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserService {

    private final static Logger log = LoggerFactory.getLogger(UserService.class);

    @Value("${secret}")
    private String secret;

    @Autowired
    UserDao userDao;

    @Autowired
    UserRoleDao userRoleDao;

    public AjaxResult save(String username,String name,String nickname,String phone, String pwd,List<String> listRoleId){
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("username",username);
            param.put("name",name);
            param.put("phone",phone);
            param.put("nickname", nickname);
            param.put("pwd", pwd);
            param.put("create_time", UtilDate.now());
            int ck = userDao.save(param);
            if(ck > 0){
                if(listRoleId != null && !listRoleId.isEmpty()) {
                    ck = userRoleDao.batAdd(param.get("user_id").toString(), listRoleId);
                    if (ck < 1) {
                        return AjaxResult.getFail();
                    }
                }
                return AjaxResult.getOk();
            }
        } catch (Exception e) {
            if(e.getMessage() != null) {
                if (e.getMessage().contains("Duplicate entry")) {
                    return AjaxResult.getFail("手机号已存在");
                }
                return AjaxResult.getFail(e.getMessage());
            }
            log.error("异常",e);
            return AjaxResult.getFail("对象空");
        }
        return AjaxResult.getFail();
    }

    public AjaxResult pwdLogin(String phone, String pwd){
        String old_pwd = userDao.getPwdByUsername(phone);
        if(UtilCheck.isEmpty(old_pwd) || !pwd.equals(old_pwd)){
            return AjaxResult.getFail("账号密码错误");
        }
        int ck = userDao.updateLoginTime(phone,UtilDate.now());
        if(ck < 1){
            return AjaxResult.getFail("账号密码错误");
        }
        return resToken(phone);
    }

    public AjaxResult smsLogin(String phone){
        String old_pwd = userDao.getPwdByUsername(phone);
        if(UtilCheck.isEmpty(old_pwd)){
            return AjaxResult.getFail("账号错误");
        }
        int ck = userDao.updateLoginTime(phone,UtilDate.now());
        if(ck < 1){
            return AjaxResult.getFail("更新登录时间失败");
        }
        return resToken(phone);
    }

    AjaxResult resToken(String phone){
        Map<String,Object> mapUser = userDao.getByUsername(phone);
        log.info("秘钥【{}】",secret);
        Map<String, Object> map = new HashMap<>();
        map.put(Constant.Nickname,mapUser.get("nickname"));
        map.put(Constant.Phone,phone);
        map.put(Constant.UserId,mapUser.get("user_id"));
        String user_id = mapUser.get("user_id").toString();
        //缓存凭证及权限
        List<String> listMenuUri = userDao.listMenuUri(user_id);
        String token = UtilJwt.getToken(map,secret);
        map.put(Constant.MenuId,listMenuUri);
        AppInterceptor.tokenUser.put(token,map);
        //
        Map<String, String> mapResult = new HashMap<>();
        mapResult.put("token",token);
        mapResult.put("user_id",user_id);
        mapResult.put("key",Constant.Authorization);
        return AjaxResult.getOk("登录成功",mapResult);
    }


    public AjaxResult update(String user_id, String username,String name,String phone,String nickname
            , String pwd,List<String> listRoleId) {
        if(!UtilCheck.isEmpty(pwd)){
            pwd = UtilMD5.getMD5(pwd);
        }
        int ck = userDao.update(user_id,username,name,phone,nickname,pwd);
        if(ck < 1){
            return AjaxResult.getFail();
        }
        userRoleDao.delByUserId(user_id);
        if(listRoleId != null && !listRoleId.isEmpty()) {
            ck = userRoleDao.batAdd(user_id, listRoleId);
            if (ck < 1) {
                return AjaxResult.getFail();
            }
        }
        return AjaxResult.getOk();
    }

    public AjaxResult del(String user_id) {
        String username = userDao.getUsername(user_id);
        if("admin".equals(username)){
            return AjaxResult.getFail("无权删除最高管理员");
        }
        int ck = userDao.del(user_id);
        if(ck < 1){
            return AjaxResult.getFail();
        }
        return AjaxResult.getOk();
    }

    public AjaxResult list(String nickname,String phone, String pageNum, String pageSize) {
        PageHelper.startPage(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
        List<Map<String,Object>> list = userDao.list(nickname,phone);
        if(!list.isEmpty()){
            List<Map<String,Object>> listUserRole = userRoleDao.listRoleName(list.stream().map(g->g.get("user_id").toString()).collect(Collectors.toList()));
            list.forEach(f->{
                String role_name = "";
                List<String> role_id = new ArrayList<>();
                String user_id = f.get("user_id").toString();
                if(!listUserRole.isEmpty()){
                    role_name = listUserRole.stream().filter(g->user_id.equals(g.get("user_id").toString()))
                            .map(g->g.get("role_name").toString()).collect(Collectors.joining("、"));
                    role_id = listUserRole.stream().filter(g->user_id.equals(g.get("user_id").toString()))
                            .map(g->g.get("role_id").toString()).collect(Collectors.toList());
                }
                f.put("role_name",role_name);
                f.put("role_id",role_id);
            });
        }
        return AjaxResult.getOk(new PageInfo<>(list));
    }

    public AjaxResult configRoles(String user_id, List<String> list) {
        userRoleDao.delByUserId(user_id);
        userRoleDao.batAdd(user_id,list);
        return AjaxResult.getOk();
    }

    public AjaxResult getMenuList(String user_id) {
        String user_name = userDao.getUserName(user_id);
        List<Map<String,Object>> list;
        if("admin".equals(user_name)){
            list = userDao.listMenuAll();
        }else{
            list = userDao.listMenu(user_id);
        }
        List<Map<String,Object>> listResult = new ArrayList<>();
        if(!list.isEmpty()){
            List<Map<String,Object>> listRoot = list.stream().filter(g->"0".equals(g.get("pid").toString())).collect(Collectors.toList());
            listRoot = listRoot.stream().sorted(Comparator.comparingInt(g->Integer.valueOf(g.get("menu_order").toString()))).collect(Collectors.toList());
            for(Map<String,Object> mapRoot:listRoot){
                String menu_id = mapRoot.get("menu_id").toString();
                //
                Map<String,Object> map = new HashMap<>();
                map.putAll(mapRoot);
                List<Map<String,Object>> children = new ArrayList<>();
                List<Map<String,Object>> listChildren = list.stream().filter(g->menu_id.equals(g.get("pid").toString())).collect(Collectors.toList());
                listChildren = listChildren.stream().sorted(Comparator.comparingInt(g->Integer.valueOf(g.get("menu_order").toString()))).collect(Collectors.toList());
                for(Map<String,Object> mapChildren:listChildren) {
                    Map<String, Object> map2 = new HashMap<>();
                    map2.putAll(mapChildren);
                    children.add(map2);
                }
                map.put("children",children);
                listResult.add(map);
            }
        }
        return AjaxResult.getOk(listResult);
    }


    public AjaxResult select(String phone) {
        List<Map<String,Object>> list = userDao.listByUsername(phone);
        return AjaxResult.getOk(list);
    }
}
